//
//  CustomTabBar.swift
//  SinaBlog
//
//  Created by 李超 on 16/3/20.
//  Copyright © 2016年 lichao. All rights reserved.
//

import UIKit
import SVProgressHUD

let itemCount = 5
class CustomTabBar: UITabBar {
    //添加编辑按钮被触发后处理的闭包
    var addComposeBtnActionHandler:(() -> ())?
    
    //重新调整位置,重写布局子控件的方法
    override func layoutSubviews() {
        //调用父类方法，完成父类控件的布局
        super.layoutSubviews()
        //取得平均宽度
        let width = frame.width / CGFloat(itemCount)
        var index = 0
        //只需要更改barButton的位置，需要通过类别确认
        //print(subviews)
        let cl = NSClassFromString("UITabBarButton")
        //遍历barButton
        for subview in subviews {
            if subview.isKindOfClass(cl!){
                subview.frame = CGRect(x: width * CGFloat(index), y: 0, width: width, height: frame.height)
                
                index++
                if index==2{
                    index++
                }
                
            }
        }
       //设置btn的frame
     composeBtn.frame = CGRect(x: width * CGFloat(2), y: 0, width: width, height: frame.height)
    }
    //懒加载自定义btn，懒加载需要注意大括号后面有个小括号
    private lazy var composeBtn:UIButton = {
        
       let btn = UIButton()
       btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
      btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
      btn .setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
      btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        //添加点击事件
        btn.addTarget(self, action: "composeBtnDidAction", forControlEvents: UIControlEvents.TouchUpInside)
        //添加到tabBar中
       self.addSubview(btn)
      
       return btn
    }()
    //点击编辑按钮触发的方法
    func composeBtnDidAction(){
        //需要先判断用户有无登陆，如果没有登陆，则不应该进行跳转
        if !CZUserAccountTool.shareInstance.userLogin {
            SVProgressHUD.showErrorWithStatus("请先登陆")
            return
        }
        //已经登陆，则进行跳转
        addComposeBtnActionHandler?()
    }
    
    
}
